var currentNav = "cartNav";

//加载购物车
window.loadcart = function loadcart() {
    sessionStorage.getItem('userId','userId');
    $("#" + currentNav).removeClass("myactive");
    currentNav = "cartNav"
    $("#" + currentNav).addClass("myactive");
    $("#innerArea").empty();
    $("#innerArea").append(`                
    <div class="col-12">
            <!-- 购物车开始 -->
            <div class="mainColumnm">
                <div class="wrap clearfix">
                    <form action="order">
                        <table width="100%" id="carttable" class="table table-bordered cartTable" cellspacing="0" cellpadding="10px">
                            <!-- 首行 -->
                                <tr class="title">
                                   
                                    <td width="100" class=""><span style="margin-left: -10px;"> 商品照片</span></td>
                                    <td width="350">商品信息</td>
                                    <td width="100">单价（元）</td>
                                    <td width="250">数量</td>
                                    <td width="150">金额（元）</td>
                                    <td width="80">操作</td>
                        </table>
                    </form>
                </div>
            </div>
            <!--购物车结束-->
        </div>`);

    let userId = sessionStorage.getItem('userId');
    console.log(userId);
    //ajax请求后端
    fetch(`http://localhost:8022/api/carts/${userId}`)
        .then((response) => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then((data) => {
            // 处理获取到的数据
            // console.log(data);
            //let datajson = data;
            let datajson = data.data;
            // console.log(datajson);
            for (let i = 0; i < datajson.length; i++) {
                $("#carttable").append(` 
                <!-- 商品具体信息 -->
                <tr class="rows title" id = "row${datajson[i].itemId}">
                    
                    <td class="tal">
                       <a href="Item?productId=${datajson[i].itemId}&categoryId=${datajson[i].itemId}"
                           class="pic"> 
                            <img width="50" height="50" style="border-radius: 5px"
                                 src="${datajson[i].description}"
                                 alt="${datajson[i].itemId}">
                                </a> 
                    </td>
                    <td class="tal">${datajson[i].itemId}
                    </td>
                    <td>
                        <b id = "price${datajson[i].itemId}" class="unit">${datajson[i].price}</b>
                    </td>
                    <td>
                        <div class="amount">
                            <a href="#" id = "${datajson[i].itemId}" class="Increase" onclick="doIncrease('${datajson[i].itemId}','${datajson[i].quantity}')">+</a>
                            <form name="quantityFrm" action="cartEdit">
                                <input type="text" id="${datajson[i].itemId}" name="quantity" class="unum" readonly="readonly"
                                       value=${datajson[i].quantity}>
                            </form>
                            <a href="#" id = "${datajson[i].itemId}" class="Reduce" onclick="doReduce('${datajson[i].itemId}','${datajson[i].quantity}')">-</a>
                        </div>
                    </td>
                    <td><b id = "up${datajson[i].itemId}" class="u-price"></b></td>
                    <td><a href="#" id="${datajson[i].itemId}" onclick="doDel('${datajson[i].itemId}')" class="btn-del">删除</a>
                    </td>
                </tr>`);
            }
            $("#carttable").append(`
            <tr class="count">
            <td colspan="7">
            <div class="jiesuan clearfix">
            <div class="left fl" style="text-align:left">
            
            </div>
            <div class="right fr clearfix" style="text-align:right">
        
            <p>已选商品<span class="red t-number"> 0 </span>件 总价(不含运费、税费)：<span
            class="red t-price">￥0.00</span>
            </p>
            <input value="结算" type="submit" id="payfr"
            class="btn pay fr"/>
            </div>
            </div>
            </td>
            </tr>
            `);
            setUprice();
            setTotal();
        })
        .catch((error) => {
            // 处理错误信息
            console.error("购物车无商品");
        });
    
}
//用于打开页面时统计每个商品的小计价格
window.setUprice = function setUprice() {
    // 重新获取行
    rows = document.querySelectorAll(".rows");
    // 遍历所有行
    for (var i = 0; i < rows.length; i++) {
        // 获取单价（得到的是字符串，不是数字，需要转化）
        var unitprice = rows[i].querySelector(".unit").innerHTML;
        // console.log(unitprice);
        // 获取商品数量
        var num = rows[i].querySelector(".unum").value;
        // 把单价，商品数量转化为数字
        unitprice = Number(unitprice);
        num = Number(num);
        // 计算商品现在的小计价格
        var uprice = num * unitprice;
        // 保留两位小数
        uprice = uprice.toFixed(2);

        // 把总计放在它应在的位置
        var utotalPrice = rows[i].querySelector(".u-price");
        utotalPrice.innerHTML = uprice;
    }
}
// 计算总计价格 & 计算选中的商品总数 & 同时判断是否全选
window.setTotal = function setTotal() {
    var total = 0;  // 商品总价
    var allNum = 0; // 商品总数
    // 重新获取行
    rows = document.querySelectorAll(".rows");
    // 遍历所有行
    for (var i = 0; i < rows.length; i++) {
        // 获取小计价格（得到的是字符串，不是数字，需要转化）
        var smallTotal = rows[i].querySelector(".u-price").innerHTML;
        // 获取商品数量
        var num = rows[i].querySelector(".unum").value;
        // 把小计价格转化为数字
        smallTotal = Number(smallTotal);
        total += smallTotal;
        // 计算商品总数
        num = Number(num);
        allNum += num;
    }
    // 把总计放在它应在的位置
    var totalPrice = document.querySelector(".t-price");
    totalPrice.innerHTML = "￥" + total.toFixed(2);
    // 设置商品总数
    document.querySelector(".t-number").innerHTML = allNum;
}

// 删除物品
window.doDel = function doDel(id){
    fetch(`http://localhost:8022/api/carts/1/items/${id}`,{
        method:'DELETE'
    })
    .then((response) => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })   
    .catch((error) => {
        // 处理错误信息
        console.error("无法删除");
    })
    .finally(()=>{
        console.log("处理完成");
        loadcart();
        setUprice();
        setTotal();
    })
}
// 增加物品数量
window.doIncrease = function doIncrease(id,quantity){
    var num = 1 + Number(quantity);
    fetch(`http://localhost:8022/api/carts/1/items/${id}?quantity=${num}`,{
        method:'PATCH',
    })
    .then((response) => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })   
    .catch((error) => {
        // 处理错误信息
        console.error("无法删除");
    })
    .finally(()=>{
        console.log("增加完成");
        loadcart();
        setUprice();
        setTotal();
        
    })
 
}

// 减少物品数量
window.doReduce = function doReduce(id,quantity){
    var num = Number(quantity) - 1;
    fetch(`http://localhost:8022/api/carts/1/items/${id}?quantity=${num}`,{
        method:'PATCH',
    })
    .then((response) => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })   
    .catch((error) => {
        // 处理错误信息
        console.error("无法删除");
    })
    .finally(()=>{
        console.log("减少完成");
        loadcart();
        setUprice();
        setTotal();
    })
}